package com.blank.serviceImpl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import com.blank.model.ExpressStatus;
import com.blank.service.ExpressStatusService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class ExpressStatusServiceImple implements ExpressStatusService {

	@Override
	public ArrayList<ExpressStatus> getByNu(String nu) {

		ArrayList<ExpressStatus> ess = new ArrayList<>();
		try {
			String url = Jsoup.connect("http://www.kuaidi100.com/applyurl?key=ea8027e5a2fcf3cd&com=ems&nu=" + nu)
					.data("query", "Java").userAgent("Mozilla").cookie("auth", "token").timeout(3000).get()
					.select("body").html();
			Document insidedoc = Jsoup.connect(url).data("query", "Java").userAgent("Mozilla").cookie("auth", "token")
					.timeout(3000).get();
			String html = insidedoc.toString();

			Document json = Jsoup
					.connect("http://www.kuaidi100.com/query?id=1&type=ems&postid="
							+ html.substring(html.indexOf("var nu=\"") + 8, html.indexOf("\";init")))
					.data("query", "Java").userAgent("Mozilla").cookie("auth", "token").timeout(3000).get();
			ObjectMapper objectMapper = new ObjectMapper();

			JsonNode tree = objectMapper.readTree(json.select("body").html());
			JsonNode datanode = tree.path("data");
			Iterator<JsonNode> it = datanode.iterator();

			while (it.hasNext()) {
				ess.add(objectMapper.readValue(it.next().toString(), ExpressStatus.class));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ess;
	}

}
